package com.atguigu.daijia.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class CosServiceImpl implements CosService {

    private final COSClient cosClient;

    @Value("${tencent.cloud.bucketPrivate}")
    private String bucketPrivate;

    @SneakyThrows
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {

        // 元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());

        // 向存储桶中保存文件
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replace("-", "") + fileType;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketPrivate, uploadPath, file.getInputStream(), meta);
        putObjectRequest.setStorageClass(StorageClass.Standard);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        log.info(JSON.toJSONString(putObjectResult));

        // 封装返回对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        // 图片临时访问url，回显使用
        String imageUrl = getImageUrl(uploadPath);
        cosUploadVo.setShowUrl(imageUrl);

        return cosUploadVo;
    }

    @Override
    public String getImageUrl(String path) {
        if (StringUtils.isBlank(path)) {
            return "";
        }

        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
                bucketPrivate, path, HttpMethodName.GET);
        // 设置临时URL有效期为15分钟
        Date expiration = new DateTime().plusMinutes(15).toDate();
        request.setExpiration(expiration);
        URL url = cosClient.generatePresignedUrl(request);
        return url.toString();
    }
}
